<%@ page language="java" import="java.lang.*"  pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%
	String path = request.getContextPath();
%>
<div class="widget-box" style="border:10px;margin:10px">
    <input type="hidden" id="receiptmanage_rece_receiptId" name="id" value="${receipt.id}" />
	<div id="receiptmanage_rece_grid-div-c" style="width:100%;margin:10px auto;">
        <div id="receiptmanage_rece_fixed_tool_div" class="fixed_tool_div detailToolBar">
             <div id="receiptmanage_rece___toolbar__-c" style="float:left;overflow:hidden;"></div>
        </div>
		<table id="receiptmanage_rece_grid-table-c" style="width:100%;height:100%;"></table>
		<div id="receiptmanage_rece_grid-pager-c"></div>
	</div>
</div>
<script type="text/javascript">
var context_path = '<%=path%>';
var receiptId=$("#receiptmanage_rece_receiptId").val();
var oriDataDetail;
var _grid_detail; //表格对象
var lastsel2;
var amountMsg="请确认收货数量填写正确，确认收货后数据将不能修改";

//单元格编辑成功后，回调的函数
	var editFunction = function eidtSuccess(XHR){
		 var data = eval("("+XHR.responseText+")"); 
		if(data["msg"]!=""){
			layer.alert(data["msg"]);
		}
		jQuery("#receiptmanage_rece_grid-table-c").jqGrid('setGridParam', 
				{
					postData: {
						id:$('#receiptmanage_rece_id').val(),
						queryJsonString:""
					} 
				}
		  ).trigger("reloadGrid");
	};
	
  
  	_grid_detail=jQuery("#receiptmanage_rece_grid-table-c").jqGrid({
         url : context_path + '/ASNmanage/detailList?receiptId='+receiptId,
         datatype : "json",
         colNames : [ '详情主键','物料编号','物料名称','数量','实际收货数量'],
         colModel : [ 
  					  {name : 'id',index : 'id',width : 20,hidden:true}, 
  					  {name : 'materialNo',index:'materialNo',width :20}, 
                      {name : 'materialName',index:'materialName',width : 20}, 
                      {name : 'amount',index:'amount',width : 20},
                      {name: 'actAmount', index: 'actAmount', width: 60,editable : true,editrules: {custom: true, custom_func: numberRegex},
                        editoptions: {
	                          size: 25,
	                          dataEvents: [
	                              {
	                                  type: 'blur',     
	                                  fn: function (e) {
	                                	  var $element = e.currentTarget;
	                                	  var $elementId = $element.id;
	                                	  var rowid = $elementId.split("_")[0];
	                                	  var id=$element.parentElement.parentElement.children[0].textContent;
	                                	  var indocType = 1;
	                                		  var reg = new RegExp("^[0-9]+(.[0-9]{1,2})?$");
	                                		  if (!reg.test($("#"+$elementId).val())) {
	                                			  layer.alert("非法的数量！(注：可以有两位小数的正实数)");
	                                			  return;
	                                		  }
	                                	  $.ajax({
	                                		  url:context_path + '/ASNmanage/updateReceiptAmount',
	                                		  type:"POST",
	                                		  data:{id:id,amount:$("#"+rowid+"_actAmount").val()},
	                                		  dataType:"json",
	                                		  success:function(data){
	                                		        if(Boolean(data.hasZero)) amountMsg="单据包含物料实际收货数量为0，真的确认收货吗？";
	                                		        else amountMsg="请确认收货数量填写正确，确认收货后数据将不能修改";
	                                		        if(!data.result) layer.alert(data.msg);
	                                		        $("#receiptmanage_rece_grid-table-c").jqGrid('setGridParam', 
                                							{
                                					    		url : context_path + '/ASNmanage/detailList?receiptId='+receiptId,
                                								postData: {queryJsonString:""} //发送数据  :选中的节点
                                							}
                                					  ).trigger("reloadGrid");
	                                		  }
	                                	  }); 
	                                  }
	                              }
	                          ]
	                      }
                      },
                    ],
         rowNum : 20,
         rowList : [ 10, 20, 30 ],
         pager : '#receiptmanage_rece_grid-pager-c',
         sortname : 'ID',
         sortorder : "asc",
         altRows: true,
         viewrecords : true,
         autowidth:true,
		 multiboxonly: true,
         loadComplete : function(data){
             var table = this;
             setTimeout(function(){updatePagerIcons(table);enableTooltips(table);}, 0);
             oriDataDetail = data;
         },
	     cellEdit: true,
	     cellsubmit : "clientArray",
  	     emptyrecords: "没有相关记录",
  	     loadtext: "加载中...",
  	     pgtext : "页码 {0} / {1}页",
  	     recordtext: "显示 {0} - {1}共{2}条数据",
    });
    //在分页工具栏中添加按钮
    $("#receiptmanage_rece_grid-table-c").navGrid('#receiptmanage_rece_grid-pager-c',{edit:false,add:false,del:false,search:false,refresh:false}).navButtonAdd('#receiptmanage_rece_grid-pager-c',{  
  	   caption:"",   
  	   buttonicon:"ace-icon fa fa-refresh green",   
  	   onClickButton: function(){   
  	    $("#receiptmanage_rece_grid-table-c").jqGrid('setGridParam', 
				{
  	    			url:context_path + '/ASNmanage/detailList?receiptId='+receiptId,
					postData: {queryJsonString:""} //发送数据  :选中的节点
				}
		  ).trigger("reloadGrid");
  	   }
  	});
  	
  	$(window).on('resize.jqGrid', function () {
  		$("#receiptmanage_rece_grid-table-c").jqGrid("setGridWidth", $("#receiptmanage_rece_grid-div-c").width() - 3 );
  		var height = $(".layui-layer-title",_grid_detail.parents(".layui-layer")).height()+
                     $("#receiptmanage_rece_materialDiv").outerHeight(true)+$("#receiptmanage_rece_grid-pager-c").outerHeight(true)+
                     $("#receiptmanage_rece_fixed_tool_div.fixed_tool_div.detailToolBar").outerHeight(true)+
                     $("#gbox_receiptmanage_rece_grid-table-c .ui-jqgrid-hdiv").outerHeight(true);
                     $("#receiptmanage_rece_grid-table-c").jqGrid('setGridHeight',_grid_detail.parents(".layui-layer").height()-height);
  	});
  	$(window).triggerHandler('resize.jqGrid');
  
//将数据格式化成两位小数：四舍五入
 function formatterNumToFixed(value,options,rowObj){
	if(value!=null){
		var floatNum = parseFloat(value);
		return floatNum.toFixed(2);
	}else{
		return "0.00";
	}
 } 
 //数量输入验证
function numberRegex(value, colname) {
    var regex = /^\d+\.?\d{0,2}$/;
    reloadDetailTableList();
    if (!regex.test(value)) return [false, ""];
    else  return [true, ""];
}

 //清空物料多选框中的值
 function removeChoice(){
	  $("#s2id_materialInfor .select2-choices").children(".select2-search-choice").remove();
	  $("#receiptmanage_rece_materialInfor").select2("val","");
	  selectData = 0;
 }

//添加物料详情
 function addDetail(){
	  if($("#receiptmanage_rece_receiptId").val()==""){
		  layer.alert("请先保存表单信息！");
		  return;
	  }
	  if(selectData!=0){
		  //将选中的物料添加到数据库中
		  $.ajax({
			  type:"POST",
			  url:context_path + '/ASNmanage/saveDetail',
			  data:{receiptId:$('#receiptmanage_rece_baseInfor #receiptmanage_rece_receiptId').val(),materialIds:selectData.toString()},
			  dataType:"json",
			  success:function(data){
				  removeChoice();   //清空下拉框中的值
				  if(Boolean(data.result)){
						layer.msg("添加成功",{icon:1,time:1200});
					  //重新加载详情表格
					  reloadDetailTableList();
				  }else{
					  layer.msg(data.msg,{icon:2,time:1200});
				  }
			  }
		  });
	  }else{
		  layer.alert("请选择物料！");
	  }
  }
  //工具栏
	  $("#receiptmanage_rece___toolbar__-c").iToolBar({
	   	 id:"receiptmanage_rece___tb__01",
	   	 items:[
	   	  	{label:"确认收货", onclick:sureReceipt},
	    ]
	  });
	//删除物料详情
function sureReceipt(){
	var ids = jQuery("#receiptmanage_rece_grid-table-c").jqGrid('getGridParam', 'selarrrow');
	layer.confirm(amountMsg,function(){
	    $.ajax({
	      url:context_path + '/ASNmanage/sureReceipt?receiptId='+$("#receiptmanage_rece_receiptId").val(),
	      type:"POST",
	      dataType:"JSON",
	      success:function(data){
	         if(data.result){
	           layer.closeAll();
	           layer.msg("操作成功！",{time:1200,icon:1});
	            //重新加载表格
				_grid.trigger("reloadGrid");  //重新加载表格  
	         }
	      }
	   });
	});
}
	
	function reloadDetailTableList(){
		$("#receiptmanage_rece_grid-table-c").jqGrid('setGridParam', 
			{
				postData: {receiptId:$("#receiptmanage_rece_baseInfor #receiptmanage_rece_receiptId").val()} //发送数据  :选中的节点
			}
	  	).trigger("reloadGrid");
	}
  </script>
